# coding=UTF-8
'''
Created on 2018年4月25日

@author: lijie
'''
import urllib

import requests

from utilites.common import Common


class HttpHelper():
    
    def __init__(self):
        '''获取driver对象，和接口ip地址信息
        '''
        run_info=Common().get_current_run_config()
        self.app_info=Common().get_app_config()[run_info['_envir']]       
    
    def post(self,module,interface_name,para={},is_url_param=False):
        '''arg: module  模块名
                interface_name   接口名称
                para     请求参数
                is_url_param   是否通过url传参
        '''
        url=''
        inter_info=Common().get_interface_info()[module]
        if is_url_param:
            postdata={}
            url=self.app_info['url']+inter_info[interface_name]['url']+'?'
            param=list(para.items())
            i=0
            for p in param:
                i+=1
                if i==len(param):
                    url=url+p[0]+'='+p[1]
                else:
                    url=url+p[0]+'='+p[1]+'&'
        else:
            url=self.app_info['url']+inter_info[interface_name]['url']
            postdata = bytes(urllib.parse.urlencode(para), encoding='utf8') 
            Common().logger_info("request - arg - "+str(para))
#         url_m=url.split('/')[3]
        Common().logger_info("request - api - "+url)
        header={
            'Accept':'*/*'
            }
        Common().logger_info("[header] - "+str(header))
        try:
#             req=urllib.request.Request(url,postdata,header)
            rs=requests.post(url,postdata,header)
            Common().logger_info('response - '+str(rs.json()))
            if rs != '':
                Common().logger_info('http post success!!!')
            return rs.json()
        except Exception as e:
            Common().logger_error(str(e))
            
    def get(self,module,interface_name,para={}):
        inter_info=Common().get_interface_info()[module]
        url=self.app_info['url']+inter_info[interface_name]['url']
        data = bytes(urllib.parse.urlencode(para), encoding='utf8') 
        Common().logger_info("request - arg - "+str(para))
        Common().logger_info("request - api - "+url)
        header={
            'Accept':'*/*'
            }
        Common().logger_info("[header] - "+str(header))
        try:
            rs=requests.get(url,params=data,headers=header)
            Common().logger_info('response - '+str(rs.json()))
            if rs != '':
                Common().logger_info('http get success!!!')
            return rs.json()
        except Exception as e:
            Common().logger_error(str(e))
